<template>
    <div class="table-box">
        <div class="card table-search">
            <el-form label-width="auto" :inline="true">
                <el-form class="search-form">
                    <!-- 经销商名称输入框 -->
                    <el-form-item label="订单编号">
                        <el-input v-model="initParam.orderNum" placeholder="请输入订单编号" style="width: 200px" />
                    </el-form-item>

                    <!-- 查询/重置按钮 -->
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="getTableList">搜索</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-form>
        </div>

        <div class="card ">
            <el-row :gutter="10" class="mb8">
                <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                    <el-tab-pane label="全部" name=""></el-tab-pane>
                    <el-tab-pane label="待审批" name="0"></el-tab-pane>
                    <el-tab-pane label="待发货" name="1"></el-tab-pane>
                    <el-tab-pane label="待收货" name="2"></el-tab-pane>
                    <el-tab-pane label="已收货" name="3"></el-tab-pane>
                    <el-tab-pane label="已驳回" name="10"></el-tab-pane>
                </el-tabs>

            </el-row>

            <div class="operation-box">
                <!-- 修改循环数据源为mockList -->
                <div class="operation-item" v-for="(item, index) in mockList" :key="item.id">
                    <div class="item-main">
                        <div class="left-info">
                            <div class="text-info">
                                <p class="shop-name">{{ item.carrierName }} {{ item.orderNum }}</p>
                                <p class="contact-info">创建于 | {{ item.createTime }}</p>
                                <p class="contact-info">共{{ item.detailNum }}款样品</p> <!-- 动态显示产品数 -->
                                <p class="contact-info" v-if="item.logisticsNum">共{{ item.logisticsNum }}</p>
                                <p class="contact-info" v-if="item.status === 2 && item.trackingNumber">快递单号：{{
                                    item.trackingNumber }}</p>
                            </div>
                        </div>
                        <div class="right-actions">
                            <!-- 状态标签与Switch组合 -->
                            <div class="status-group">
                                <el-tag :type="getStatusTagType(item.status)" effect="light" size="small">
                                    {{ getStatusText(item.status) }}
                                </el-tag>
                                <!-- 新增Switch开关 -->
                                <el-switch v-if="item.status == 2 || item.status == 3" v-model="item.isProductList"
                                    :disabled="item.isProductList == 1" :active-value="1" :inactive-value="0"
                                    active-text="已下成品" inactive-text="未下成品"
                                    :before-change="() => { handleStatusChange(item) }" style="margin-left: 8px;" />
                            </div>
                            <el-button v-if="item.status === 1" type="text" icon="Upload"
                                @click="handleUploadLogistics(item)">
                                上传物流信息
                            </el-button>
                            <el-button type="text" icon="EditPen" @click="openDiolg('编辑', item)">编辑并查看</el-button>

                        </div>
                    </div>
                </div>
            </div>
            <pagination :total="totals" v-model:page="initParam.pageNum" v-model:limit="initParam.pageSize"
                @pagination="getTableList" />
        </div>

        <el-dialog v-model="logisticsDialogVisible" title="上传物流信息" width="30%">
            <el-form :model="logisticsForm" :rules="logisticsRules" label-width="100px">
                <el-form-item label="快递单号" prop="trackingNumber">
                    <el-input v-model="logisticsForm.trackingNumber" placeholder="请输入快递单号" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="logisticsDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitLogistics">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.operation-box {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    /* 项间距 */
    padding: 20px;
}

.operation-item {
    width: calc((100% - 40px) / 3);
    border: 1px solid #f0f2f5;
    /* 更浅的边框颜色 */
    border-radius: 12px;
    /* 更大的圆角 */
    padding: 20px;
    /* 增加内边距 */
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
    /* 更柔和的阴影 */
    transition: all 0.3s ease;
    /* 添加过渡动画 */

    &:hover {
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
        /* 悬停阴影加深 */
        transform: translateY(-2px);
        /* 轻微上移效果 */
    }
}

.item-main {
    align-items: center;
    /* 垂直居中对齐 */
}

.left-info .text-info {
    .shop-name {
        color: black;
        font-size: 18px;
        /* 增大标题字号 */
        margin-bottom: 8px;
        /* 增加标题与其他信息的间距 */
    }

    .contact-info {
        font-size: 13px;
        /* 缩小辅助信息字号 */
        color: #909399;
        /* 更浅的辅助文字颜色 */
    }
}

.right-actions {
    flex-direction: row;
    /* 改为水平排列 */
    align-items: center;
    /* 垂直居中 */
    gap: 12px;
    /* 统一元素间距 */
}

.status-group {
    display: flex;
    /* 状态标签与Switch水平排列 */
    align-items: center;
}

.el-switch {
    --el-switch-width: 40px;
    /* 调整开关宽度 */
    --el-switch-height: 20px;
    /* 调整开关高度 */
}

.status-tag {
    font-size: 14px;
    padding: 2px 8px;
    border-radius: 12px;
}

.status-tag.active {
    background: #e6f4ea;
    color: #67c23a;
}

.status-tag.inactive {
    background: #fde2e2;
    color: #f56c6c;
}

.auth-series {
    margin-top: 12px;
}

.series-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
}
</style>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, tabBarProps } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import {
    ColumnProps,
} from "@/components/ProTable/interface";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    listOrder,
    getOrder,
    delOrder,
    addOrder,
    updateOrder,
    approve,
    send
} from "@/api/zc/order/index.js";
import {
    listCompare,
    getCompare,
    delCompare,
    addCompare,
    updateCompare,
    enable
} from "@/api/zc/compare";

import { getDicts } from "@/api/system/dict/data";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { useHandleData } from "@/hooks/useHandleData";
import CryptoJS from 'crypto-js';
const proxy = getCurrentInstance()?.proxy;
const emit = defineEmits(["changeItem"]);
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));
const publicKey = import.meta.env.VITE_APP_PUBLICKEY; //引入公钥
const router = useRouter();
const ExcelRef = ref(null);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<any>();
let memberFiled = { label: "dealerName", value: "id", labelName: "dealerName", autoLable: false };
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
    compareName: '',  // 经销商名称
    belong: '',       // 所属机构ID
    status: '',       // 所属状态（0/1）
    pageNum: 1,
    pageSize: 6,
    orderNum: ""
});
const getStatusText = (status) => {
    const statusMap = {
        '0': '待审批',
        '1': '待发货',
        '2': '待收货',
        '3': '已收货',
        '10': '已驳回'
    };
    return statusMap[status] || '未知状态';
};

const getStatusTagType = (status) => {
    const typeMap = {
        '0': 'warning',    // 待审批 - 黄色
        '1': 'primary',    // 待发货 - 蓝色
        '2': 'info',       // 待收货 - 浅蓝色
        '3': 'success',    // 已收货 - 绿色
        '10': 'danger'     // 已驳回 - 红色
    };
    return typeMap[status] || 'info';
};
onMounted(() => {
    setTimeout(() => {
        const { index, ...query } = router.currentRoute.value.query;
        if (index == 0) {
            activeTab.value = index;
            handleTabChange(index);
            // 成功后移除add参数
            router.replace({ query });
        }
    }, 1000)
})
// 添加响应式数据
const logisticsDialogVisible = ref(false);
const logisticsForm = reactive({
    trackingNumber: '',
    currentOrder: null
});

const logisticsRules = reactive({
    trackingNumber: [
        { required: true, message: '请输入快递单号', trigger: 'blur' }
    ]
});
// 修改handleUploadLogistics方法
const handleUploadLogistics = (item) => {
    logisticsForm.currentOrder = item;
    logisticsForm.trackingNumber = item.logisticsNum || ''; // 如果有已有物流号则填充
    logisticsDialogVisible.value = true;
};

// 添加提交物流信息方法
const submitLogistics = async () => {
    if (!logisticsForm.trackingNumber) {
        ElMessage.warning('请输入快递单号');
        return;
    }

    try {
        // 这里调用更新物流信息的API
        await send({
            ...logisticsForm.currentOrder,
            logisticsNum: logisticsForm.trackingNumber,
            status: 2
        });

        ElMessage.success('物流信息上传成功');
        logisticsDialogVisible.value = false;
        getTableList(); // 刷新列表
    } catch (error) {
        ElMessage.error('物流信息上传失败');
    }
};
const totals = ref(0);
const resetQuery = () => {
    initParam.orderNum = '';
    getTableList();
}
const activeTab = ref('');

const handleTabChange = (tabName) => {
    console.log("tabName", tabName)
    initParam.status = tabName;
    getTableList();
};
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
    return { list: data.rows, total: data.total };
};

const handleStatusChange = async (item: any) => {
    if (item.isProductList == 0) {
        try {
            await updateOrder({ ...item, isProductList: 1 });  /* 调用更新状态接口 */
            ElMessage.success(`切换为${item.isProductList === '1' ? '已下成品' : '已下成品'}成功`);
            getTableList();  /* 刷新列表数据 */
            return true;


        } catch (error) {
            ElMessage.error('状态切换失败');
            return false;
            // 回滚状态（如果接口调用失败）
            // item.status = item.status === '1' ? '0' : '1';
        }
    }

};
// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const ableList = ref([])
const getTableList = async () => {
    let { rows, total } = await listOrder({ ...initParam, activeTab: activeTab.value });
    // mockList.value = rows.map((item: any) => {
    //     return {
    //         ...item,
    //         optionalSeries: item.optionalSeries.split(','),
    //     };
    // });
    mockList.value = rows;
    totals.value = total;

    // let { rows: data } = await listCompare({ ...initParam, enable: 0 });
    // ableList.value = data;
    // return listSupplier(params);
};
getTableList();
const templateParams = {
    templateName: "demo模板",
    templateUrl: "system/user/importTemplate",
    templateType: 0,
    templateObj: {}
}


const changeStatus = async (row: any, key: string) => {
    // await useHandleData(updateSign, { ...row, key: row[key] == 1 ? 0 : 1 }, `切换状态`);
    await enable({ ...row, key: row[key] == 1 ? 0 : 1 });
    ElMessage.success({ message: `调整状态成功！` });
    proTable.value?.getTableList();
};
// 删除用户信息
const deleteAccount = async (params: any) => {
    const ids = params.id
    await useHandleData(delCompare, ids, '是否删除编号为' + ids + '的数据');
    getTableList();
};
//模拟 调用接口
const PromiseDel = () => new Promise((resolve, reject) => resolve(true))

/** 导出按钮操作 */
function handleExport() {
    proxy.download("system/user/export", {

    }, `user_${new Date().getTime()}.xlsx`);
};

const openDiolg = async (title: string, rowData: any) => {
    let params: any = {
        title,
        isView: title === "查看",
        rowData: { ...rowData },
        api: title === "新增" ? addCompare : title === "编辑" ? approve : approve,
        getTableList: proTable.value?.getTableList,
    };
    if (title === "新增") {
        params.rowData.selectedSeries = []

    } else {
        let { data } = await getOrder(rowData.id)
        params.rowData = data;
        params.rowData.carrierName = rowData.carrierName;
        console.log(params.rowData)
    }
    emit("changeItem", "1", params, title);
};

// 新增模拟数据（包含图片地址、店名、联系方式等）
const mockList = ref([
    // {
    //     id: 1,
    //     logo: 'https://via.placeholder.com/50x50?text=杭州旗舰店', // 占位图服务
    //     shopName: '杭州旗舰店',
    //     contactName: '张经理',
    //     phone: '138-1234-5678',
    //     status: '1', // 1=启用
    //     authSeries: ['奢华印象', '经典系列']
    // },
    // {
    //     id: 2,
    //     logo: 'https://via.placeholder.com/50x50?text=上海体验店',
    //     shopName: '上海体验店',
    //     contactName: '李总监',
    //     phone: '139-8765-4321',
    //     status: '0', // 0=禁用
    //     authSeries: ['普通质感', '现代简约']
    // },
    // {
    //     id: 3,
    //     logo: 'https://via.placeholder.com/50x50?text=广州形象店',
    //     shopName: '广州形象店',
    //     contactName: '王店长',
    //     phone: '186-0000-1111',
    //     status: '1',
    //     authSeries: ['高端定制', '轻奢风尚']
    // },
    // 可根据需要添加更多模拟数据
]);
</script>
